package com.chexiehui.jc.ui.fragment;

import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aries.ui.view.title.TitleBarView;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.base.BaseMvpLazyLoadFragment;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.DictInfo;
import com.chexiehui.jc.entity.PriceConditionInfo;
import com.chexiehui.jc.entity.SpecialCarInfo;
import com.chexiehui.jc.mvp.car.SpecialCarListCovenant;
import com.chexiehui.jc.mvp.car.SpecialCarListPresenter;
import com.chexiehui.jc.ui.activity.CarSeriesDetailsActivity;
import com.chexiehui.jc.ui.activity.SpecialCarDetailsActivity;
import com.chexiehui.jc.ui.activity.SpecialCarInquiryActivity;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.widget.CustomChooseGradePopup;
import com.chexiehui.jc.widget.CustomChoosePricePopup;
import com.chexiehui.jc.widget.CustomChooseSortPopup;
import com.chexiehui.jc.widget.CustomSpecialCarInquiryPopup;
import com.chexiehui.jc.widget.LoadingLayout;
import com.lxj.xpopup.XPopup;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 特价车
 */
public class SpecialCarListFragment extends BaseMvpLazyLoadFragment<SpecialCarListPresenter> implements SpecialCarListCovenant.View,
        CustomChoosePricePopup.ICustomChoosePricePopupListener,
        CustomChooseGradePopup.ICustomChooseGradePopupListener,
        CustomSpecialCarInquiryPopup.ICustomSpecialCarInquiryPopupListener, CustomChooseSortPopup.ICustomChooseSortPopupListener {

    public static SpecialCarListFragment getInstance() {
        SpecialCarListFragment fragment = new SpecialCarListFragment();
        return fragment;
    }

    @BindView(R.id.titleBar)
    TitleBarView titleBar;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_choose_sort)
    TextView tvChooseSort;
    @BindView(R.id.rl_choose_sort)
    RelativeLayout rlChooseSort;
    @BindView(R.id.tv_choose_price)
    TextView tvChoosePrice;
    @BindView(R.id.rl_choose_price)
    RelativeLayout rlChoosePrice;
    @BindView(R.id.tv_choose_grid)
    TextView tvChooseGrid;
    @BindView(R.id.rl_choose_grid)
    RelativeLayout rlChooseGrid;
    @BindView(R.id.ll_choose_panel)
    LinearLayout llChoosePanel;
    private List<SpecialCarInfo> listData;
    private CommonAdapter<SpecialCarInfo> listAdapter;
    private BasePage<SpecialCarInfo> page;
    private CustomSpecialCarInquiryPopup inquiryPopup;
    private CustomChoosePricePopup customChoosePricePopup;
    private CustomChooseSortPopup customChooseSortPopup;
    private PriceConditionInfo choosePrice;
    private int chooseSortIndex;
    private List<DictInfo> gradList;
    private CustomChooseGradePopup customChooseGradePopup;
    private DictInfo chooseGrade;

    @Override
    protected void initTitleView(Bundle savedInstanceState) {
        titleBar.setTitleMainText("新车批发")
                .setDividerVisible(false)
                .setLeftTextDrawable(0);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_special_car_list;
    }

    @Override
    protected void initView(Bundle var1) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        gradList = new ArrayList<>();
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        loadingLayout.setOnReloadListener(v -> {
            refreshLayout.finishRefresh(false);
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        });
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (loadingLayout.getStatus() == LoadingLayout.Loading) {
                    refreshLayout.finishRefresh(false);
                    return;
                }
                mvpPresenter.getList(1);
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (page != null && page.getTotalRecordCount() > listData.size()) {
                    mvpPresenter.getList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });
        recycler.setLayoutManager(new LinearLayoutManager(mActivity));
        listData = new ArrayList<>();
        listAdapter = new CommonAdapter<SpecialCarInfo>(mActivity, R.layout.item_special_car, listData) {
            @Override
            protected void convert(ViewHolder holder, SpecialCarInfo item, int position) {
                GlideUtil.loadImageViewCrop(mContext, item.getImg(), holder.getView(R.id.iv_item_image),
                        R.drawable.shape_square, R.drawable.shape_square);
                holder.setText(R.id.tv_item_name, item.getName());
                holder.setText(R.id.tv_item_price, item.getPriceStr());
                holder.setText(R.id.tv_item_agent_price, item.getAgentPriceStr());
                holder.setVisible(R.id.tv_item_agent_price, !StringUtils.isEmpty(item.getAgentPriceStr()));
                TextView tv_item_old_price = holder.getView(R.id.tv_item_old_price);
                tv_item_old_price.setText(item.getOldPriceStr());
                tv_item_old_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                holder.setText(R.id.tv_item_ask_num, "已有" + item.getCount() + "人询价");
                holder.getView(R.id.rtv_item_ask).setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        showInquiryPopup(position);
                    }
                });
            }
        };
        listAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                startActivity(SpecialCarDetailsActivity.class, new BundleBuilder().putString("id", listData.get(position).getId()).create());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        recycler.setAdapter(listAdapter);
        isPrepared = true;
        lazyLoad();
    }

    @Override
    protected void lazyLoad() {
        if(!isVisible || !isPrepared || mHasLoadedOnce){
            return;
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getBigType();
        mvpPresenter.getList(1);
    }

    private void showInquiryPopup(int position) {
        if (inquiryPopup == null) {
            inquiryPopup = new CustomSpecialCarInquiryPopup(mActivity);
            inquiryPopup.setListener(this);
        }
        inquiryPopup.initModel(listData.get(position));
        new XPopup.Builder(mActivity)
                .autoOpenSoftInput(false)
                .asCustom(inquiryPopup)
                .show();
    }

    @Override
    protected SpecialCarListPresenter createPresenter() {
        return new SpecialCarListPresenter(this);
    }

    @Override
    public void onGetListSuccess(BaseModel<BasePage<SpecialCarInfo>> successResult) {
        mHasLoadedOnce = true;
        page = successResult.getData();
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= listAdapter.getDatas().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            mHasLoadedOnce = true;
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (listAdapter.getDatas().size() > 0) {
                    listAdapter.getDatas().clear();
                    listAdapter.notifyDataSetChanged();
                }
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
            if (listAdapter.getDatas().size() <= 0) {
                loadingLayout.setStatus(LoadingLayout.Error);
                loadingLayout.setErrorText(failureResult.getResultInfo());
            } else {
                showToast(failureResult.getResultInfo());
            }
        }
    }

    @Override
    public void onGetBigTypeSuccess(BaseModel<List<DictInfo>> successResult) {
        gradList.clear();
        gradList.addAll(successResult.getData());
        gradList.add(0, new DictInfo("", "级别不限"));
    }

    @Override
    public void onGetBigTypeFailure(BaseModel<Object> failureResult) {

    }

    @Override
    public String getSeriesId() {
        return "";
    }

    @Override
    public void onSureInquiry(SpecialCarInfo carInfo) {
        startActivity(SpecialCarInquiryActivity.class,
                new BundleBuilder().putSerializable("entity", carInfo).create());
    }

    @OnClick({R.id.rl_choose_sort, R.id.rl_choose_price, R.id.rl_choose_grid})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_choose_sort:
                showChooseSortPopup();
                break;
            case R.id.rl_choose_price:
                showChoosePricePopup();
                break;
            case R.id.rl_choose_grid:
                showChooseGradPopup();
                break;
        }
    }

    @Override
    public void onChoosePrice(PriceConditionInfo info) {
        choosePrice = info;
        tvChoosePrice.setText(info.getName());
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getList(1);
    }

    private void showChoosePricePopup() {
        if (customChoosePricePopup == null) {
            customChoosePricePopup = new CustomChoosePricePopup(mActivity);
            customChoosePricePopup.setListener(this);
        }
        customChoosePricePopup.initPriceModel(choosePrice);
        new XPopup.Builder(mActivity)
                .atView(llChoosePanel)
                .asCustom(customChoosePricePopup)
                .show();
    }

    private void showChooseSortPopup() {
        if (customChooseSortPopup == null) {
            customChooseSortPopup = new CustomChooseSortPopup(mActivity);
            customChooseSortPopup.setListener(this);
        }
        new XPopup.Builder(mActivity)
                .atView(llChoosePanel)
                .asCustom(customChooseSortPopup)
                .show();
    }

    private void showChooseGradPopup() {
        if (customChooseGradePopup == null) {
            customChooseGradePopup = new CustomChooseGradePopup(mActivity, gradList);
            customChooseGradePopup.setListener(this);
        }
        new XPopup.Builder(mActivity)
                .atView(llChoosePanel)
                .asCustom(customChooseGradePopup)
                .show();
    }

    @Override
    public void onChooseGrade(DictInfo grade) {
        chooseGrade = grade;
        tvChooseGrid.setText(grade.getValue());
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getList(1);
    }

    @Override
    public void onChooseSort(int position, String name) {
        chooseSortIndex = position;
        tvChooseSort.setText(name);
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getList(1);
    }

    @Override
    public String getPriceMin() {
        return choosePrice != null ? choosePrice.getMin() : "";
    }

    @Override
    public String getSortType() {
        return (chooseSortIndex + 1) + "";
    }

    @Override
    public String getPriceMax() {
        return choosePrice != null ? choosePrice.getMax() : "";
    }

    @Override
    public String getBigTypeId() {
        return chooseGrade != null ? chooseGrade.getKey() : "";
    }

}
